package order

import (
	"context"
	"github.com/hibiken/asynq"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"navi-mumbai/app/rpc/game/pb"
	pb2 "navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/app/timer/job/internal/svc"
	"navi-mumbai/common/key/gamekey"
	"time"
)

type SyncGamProviderY9YOrderHandler struct {
	svcCtx *svc.ServiceContext
}

func NewSyncGameProviderY9YOrderHandler(svcCtx *svc.ServiceContext) *SyncGamProviderY9YOrderHandler {
	return &SyncGamProviderY9YOrderHandler{
		svcCtx: svcCtx,
	}
}

// 定时拉取game order
func (l *SyncGamProviderY9YOrderHandler) ProcessTask(ctx context.Context, _ *asynq.Task) error {
	logx.WithContext(ctx).Info("[SyncGamProviderY9YOrderHandler] ProcessTask start...")
	var startIdx int64 = 0
	var count int64 = 0
	startTime := time.Now().Unix()
	var in pb.PullGameOrderReq
	in.Size = 100
	in.ProviderId = gamekey.ProviderIdY9Y
	var resp *pb.PullGameOrderResp
	var syncOrderReq pb2.SyncGameOrderFlowReq
	syncOrderReq.List = make([]*pb2.SyncGameOrderFlow, 0)
	var err error
	for {
		in.StartIdx = startIdx
		resp, err = l.svcCtx.GameSysRpc.PullGameOrder(ctx, &in)
		if err != nil {
			logx.WithContext(ctx).Errorf("[SyncGamProviderY9YOrderHandler] ProcessTask err:%v", err)
			return nil
		}
		if resp.Count == 0 || resp.NextIdx <= startIdx {
			break
		}
		count += resp.Count
		if time.Now().Unix()-startTime > 30 {
			break
		}
		startIdx = resp.NextIdx
		//time.Sleep(1 * time.Second)

		// 同步订单
		_ = copier.Copy(&syncOrderReq, resp)
		_, err = l.svcCtx.WalletSysRpc.SyncGameOrderFlow(ctx, &syncOrderReq)
		if err != nil {
			logx.WithContext(ctx).Errorf("[SyncGamProviderY9YOrderHandler] SyncGameOrderFlow err:%v", err)
			return nil
		}
		syncOrderReq.List = syncOrderReq.List[:0]
	}
	logx.WithContext(ctx).Infof("[SyncGamProviderY9YOrderHandler] ProcessTask end %d seconds, count:%d", time.Now().Unix()-startTime, count)
	return nil
}
